/* eslint-disable no-debugger */
import { ipcRenderer } from "electron"
import React, {
  useCallback,
  useEffect,
  useImperativeHandle,
  useState,
} from "react"
import path from "path"
import Skeleton from "antd/lib/skeleton"
import Layout from "antd/lib/layout"
import { Content } from "antd/lib/layout/layout"
import { Button, PageHeader, Result, Tag } from "antd"
import { quicktypeJSON } from "../scripts/core"
import _, {  } from "lodash"
import JSONSchemaEditor, { metaSchema } from "json-schemaeditor-antd"
import { FileMotion } from "./DataEditor"
import { getSchemaFileName } from "./EditorOption"
import { useAsync } from "./utils/Hooks"
const option = {
  lg: "zh-CN",
}

export enum EditMode {
  data,
  schema,
}

interface FileContentProps {
  route: string
  name: string
  setCurFile: (value: string) => void
  curFile: string
}

type Content = {
  data?: any
  schema?: any
}

export interface FileContentRef {
  changed: boolean
}

const genSchema = async (data: any, route: string, name: string) => {
  const schemaFileName = getSchemaFileName(name)
  // 初始化schema然后保存
  const { lines: JsonSchema } = await quicktypeJSON(
    "json-schema",
    name,
    JSON.stringify(data)
  )
  const schemaString = JsonSchema.join("\n")

  console.log("schema转换完成", schemaFileName)
  console.time("save")

  await ipcRenderer.invoke(
    "writeFile",
    path.join(route, `${schemaFileName}.json`),
    schemaString
  )

  console.timeEnd("save")
  console.log("已保存", schemaFileName)

  return JSON.parse(schemaString)
}

const loadData = (route: string, name: string) => {
  return ipcRenderer.invoke("readFile", path.join(route, `${name}.json`), {
    encoding: "utf8",
  })
}

const loadSchema = async (data: any, route: string, name: string) => {
  const isEditingSchema = name.startsWith("$schema.")
  if (isEditingSchema) {
    return metaSchema
  } else {
    const schemaFileName = getSchemaFileName(name)
    return ipcRenderer
      .invoke("readFile", path.join(route, `${schemaFileName}.json`), {
        encoding: "utf8",
      })
      .then(
        (schema) => {
          return JSON.parse(schema)
        },
        (reason) => {
          return genSchema(data, route, name)
        }
      )
      .then((schema) => {
        return schema
      })
  }
}
const loadContent = (route: string, name: string) => {
  console.log("读取开始")
  let json = undefined as any
  return loadData(route, name)
    .then((fileData) => {
      try {
        json = JSON.parse(fileData)
        console.log("数据读取完成")
        return loadSchema(json, route, name)
      } catch (error) {
        return Promise.reject("json 解析错误：\n" + error)
      }
    })
    .then((schema) => {
      return {
        data: json,
        schema,
      }
    })
}

const FileContent = (
  props: FileContentProps,
  ref: React.ForwardedRef<FileContentRef>
) => {
  const { route, name, curFile, setCurFile } = props

  // const [motion, setMotion] = useState(FileMotion.idle)

  // const [genMotion, setGenMotion] = useState(FileMotion.idle)

  const dataFileName = `${name}.json`
  const isEditingSchema = dataFileName.startsWith("$schema.")

  const [asyncContent, setContent] = useAsync(loadContent, [
    route,
    name,
  ])
  const { result: { data, schema } = {}, error, loading } = asyncContent
  const [newData, setNewData] = useState<any>(undefined)

  useImperativeHandle(
    ref,
    () => {
      return {
        changed: newData !== undefined,
      }
    },
    [newData]
  )

  // 更换文件后，changed = false
  useEffect(() => {
    console.log('change name');
    
    setNewData(undefined)
  }, [route, name, setNewData])

  const resetSchema = useCallback(
    (e: React.MouseEvent) => {
      // setGenMotion(FileMotion.save)
      genSchema(data, route, name).then((schema) => {
        setContent({ result: { data, schema }, error, loading })
        // setGenMotion(FileMotion.idle)
      })
    },
    [route, name, data]
  )

  // const saving = useAsyncTrigger()
  if (data === undefined || schema === undefined) {
    return <Skeleton active />
  }

  // 出错信息描绘
  if (error) {
    return <Result title="读取文件出错" subTitle={error} />
  }

  // 得到标签列表
  const tags = []
  if (!schema) {
    tags.push(
      <Tag color="orange" key="noschema">
        No Schema
      </Tag>
    )
  }
  if (newData !== undefined) {
    tags.push(
      <Tag color="gold" key="notsave">
        {`${isEditingSchema ? "schema" : "data"} 修改未保存`}
      </Tag>
    )
  }

  const onJsonChange = (value: any) => {
    setNewData(value)
  }

  // onSave不需要中断，结果不影响组件状态
  const onSave = () => {
    if (newData === undefined) return;

    // setMotion(FileMotion.save)
    ipcRenderer
      .invoke(
        "writeFile",
        path.join(route, dataFileName),
        JSON.stringify(newData, null, 2)
      )
      .then(
        () => {
          // 更新当时读取到的初始数据状态
          setContent({
            ...asyncContent,
            result: {
              ...asyncContent.result,
              data: newData
            }
          })
          setNewData(undefined)
        },
        (error) => {
          console.error(error)
          // setMotion(FileMotion.idle)
        }
      )
  }

  // 得到按钮列表
  const btns = isEditingSchema
    ? [
        <Button
          key="2"
          // loading={genMotion !== FileMotion.idle}
          onClick={resetSchema}
        >
          重置模式
        </Button>,
        <Button
          key="1"
          type={newData !== undefined ? "primary" : "default"}
          // loading={motion !== FileMotion.idle || genMotion !== FileMotion.idle}
          onClick={() => {
            onSave()
            const originFileName = curFile.substring(8)
            console.log(curFile, originFileName);
            
            setCurFile(originFileName)
          }}
        >
          保存并返回
        </Button>,
      ]
    : [
        <Button
          key="2"
          // loading={motion !== FileMotion.idle}
          onClick={(e) => {
            if (newData !== undefined) onSave()
            setCurFile(getSchemaFileName(name))
          }}
        >
          编辑模式
        </Button>,
        <Button
          key="1"
          type={newData !== undefined ? "primary" : "default"}
          // loading={motion !== FileMotion.idle}
          onClick={onSave}
        >
          保存
        </Button>,
      ]

  return (
    <Layout style={{ height: "100%" }}>
      <PageHeader
        title={name}
        className="site-page-header"
        tags={tags}
        extra={btns}
      ></PageHeader>
      <Layout>
        <Content
          key="content"
          style={{ height: "100%", overflow: "auto", padding: "3px" }}
        >
          <JSONSchemaEditor
            data={newData !== undefined ? newData : data}
            onChange={onJsonChange}
            schema={schema}
          />
        </Content>
      </Layout>
    </Layout>
  )
}

export default React.forwardRef(FileContent)
